package com.xvyy.tingshu.user.strategy;

import com.xvyy.tingshu.album.client.AlbumInfoFeignClient;
import com.xvyy.tingshu.common.execption.TsException;
import com.xvyy.tingshu.common.result.Result;
import com.xvyy.tingshu.model.album.TrackInfo;
import com.xvyy.tingshu.model.user.UserPaidTrack;
import com.xvyy.tingshu.user.mapper.UserPaidTrackMapper;
import com.xvyy.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * ClassName: ProcessTypePayRecordByTrack
 * Package: com.xvyy.tingshu.user.strategy
 *
 * @Description: 处理声音类型的支付记录
 * @Author: xvyy
 * @Create: 2025/2/13 - 16:08
 * @Version: v1.0
 */
@Component(value = "1002")
@Slf4j
public class ProcessTypePayRecordByTrack implements ProcessDefaultPayRecord {

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;
    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;

    @Override
    public void processPayRecord(UserPaidRecordVo userPaidRecordVo) {
        // 1. 根据订单号查询数据库,判断是否已经处理过该订单号
        String orderNo = userPaidRecordVo.getOrderNo();
        UserPaidTrack userPaidTrack = userPaidTrackMapper.selectOne(new LambdaQueryWrapper<UserPaidTrack>().eq(UserPaidTrack::getOrderNo, orderNo));
        if (userPaidTrack != null) {
            throw new TsException(201, "该声音类型的订单已经处理过，请不要重复处理");
        }
        // 2. 远程调用album微服务获取声音详情信息
        Result<TrackInfo> trackInfoResult = albumInfoFeignClient.getTrackInfoById(userPaidRecordVo.getItemIdList().get(0));
        TrackInfo trackInfoData = trackInfoResult.getData();
        Assert.notNull(trackInfoData, "远程调用album微服务获取声音详情信息失败");
        Long albumId = trackInfoData.getAlbumId();
        // 3. 保存声音类型的支付记录到数据库
        userPaidRecordVo.getItemIdList().stream().forEach(trackId -> {
            UserPaidTrack userPaidTrack1 = new UserPaidTrack();
            userPaidTrack1.setOrderNo(orderNo);
            userPaidTrack1.setUserId(userPaidRecordVo.getUserId());
            userPaidTrack1.setAlbumId(albumId);
            userPaidTrack1.setTrackId(trackId);
            int insert = userPaidTrackMapper.insert(userPaidTrack1);
            log.info("保存订单号为{}的声音类型{}，数据记录到数据库影响行数为{}", orderNo, insert > 1 ? "成功" : "失败", insert);
        });
    }

}
